package com.wu.advapplication.servise;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.wu.advapplication.MainActivity;
import com.wu.advapplication.R;
import com.wu.advapplication.utils.BaseUtil;
import com.wu.advapplication.utils.SettingsCompat;

import java.util.Timer;
import java.util.TimerTask;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

public class CustomTestService extends Service {

    private static final String TAG = "CustomTestService";
    private int position = 0;
    private WindowManager mWindowManager;
    private final Timer timerMail = new Timer();
    private static final int SERVICE_ID = 2;
    private SharedPreferences preferences;
    private TextView content;
    private EditText keyEditText;
    private Button startBtn;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Log.i(TAG, "onCreate:-------------");
        preferences = this.getSharedPreferences("ADV_APP", 0);

        //通知栏
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {   //4.3以下
            startForeground(SERVICE_ID, new Notification());
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {//4.3-7.0
            startForeground(SERVICE_ID, new Notification());
            startService(new Intent(this, ForegroundService.InnerService.class));//通过启动一个inner服务隐藏通知栏
        } else {    //8.0以上
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel("wanandroid", "wanAndroid", NotificationManager.IMPORTANCE_LOW);
            if (manager != null) {
                manager.createNotificationChannel(channel);
                Notification notification = new NotificationCompat.Builder(this, "wanandroid").build();
                startForeground(SERVICE_ID, notification);
            }

        }

        //悬浮窗
        if (mWindowManager == null) {
            mWindowManager = (WindowManager) this.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        }

        View convertView = LayoutInflater.from(getApplication()).inflate(R.layout.view_main, null);
        content = convertView.findViewById(R.id.content);
        keyEditText = convertView.findViewById(R.id.edit_key);
        startBtn = convertView.findViewById(R.id.btn_start);
        startBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                content.setText("功能正在再发中。。。。。。");
            }
        });
        InputMethodManager imm = (InputMethodManager) keyEditText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(keyEditText, InputMethodManager.SHOW_FORCED);

        LayoutParams params = new LayoutParams();
        params.x = LayoutParams.MATCH_PARENT;
        params.y = LayoutParams.MATCH_PARENT;
        params.width = LayoutParams.MATCH_PARENT;
        params.height = LayoutParams.MATCH_PARENT;
        params.gravity = Gravity.LEFT | Gravity.TOP;
        params.type = LayoutParams.TYPE_APPLICATION_OVERLAY;
        params.format = PixelFormat.RGBA_8888;
        params.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL;
        //设置 WindowManager的参数flags属性为 params.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL;

//        LayoutParams param = new LayoutParams();
//        param = new LayoutParams();
//        if (Build.VERSION.SDK_INT >= 26) {
//            param.type = LayoutParams.TYPE_APPLICATION_OVERLAY;
//        } else {
//            param.type = LayoutParams.TYPE_SYSTEM_ALERT;
//        }
//        param.flags = LayoutParams.FLAG_FULLSCREEN
//                | LayoutParams.FLAG_LAYOUT_IN_SCREEN
//                | LayoutParams.FLAG_ALT_FOCUSABLE_IM
//                | LayoutParams.FLAG_NOT_TOUCH_MODAL;
//        param.format = PixelFormat.RGBA_8888;
//        param.gravity = Gravity.CENTER;
//        param.x = LayoutParams.MATCH_PARENT;
//        param.y = LayoutParams.MATCH_PARENT;
//        // 设置悬浮窗口长宽数据
//        param.width = LayoutParams.MATCH_PARENT;
//        param.height = LayoutParams.MATCH_PARENT;
//
//        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
//                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
//        lp.gravity = Gravity.CENTER;
//
//        LinearLayout view = new LinearLayout(getApplication());
//        view.setLayoutParams(lp);// 设置布局参数
//        view.setGravity(Gravity.CENTER);
//        view.setLayoutParams(lp);
//
//        final ImageView i = new ImageView(getApplication());
//        i.setBackgroundResource(R.drawable.img_1);
//        view.addView(i);
//        i.setOnLongClickListener(new OnLongClickListener() {
//
//            @Override
//            public boolean onLongClick(View v) {
//                // TODO Auto-generated method stub
//                mWindowManager.removeView(i);
//                return false;
//            }
//        });
//
//        i.setOnClickListener(new OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                // TODO Auto-generated method stub
//                position++;
//                if (position == 1) {
//                    i.setBackgroundResource(R.drawable.img_1);
//                } else if (position == 2) {
//                    i.setBackgroundResource(R.drawable.img_2);
//                } else if (position == 3) {
//                    i.setBackgroundResource(R.drawable.img_3);
//                    position = 0;
//                }
//                Toast.makeText(getApplication(), "你再点一个试试", Toast.LENGTH_SHORT)
//                        .show();
//            }
//        });
        mWindowManager.addView(convertView, params);
    }

    private long exitTime;
    private int r = 0;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand");
        timerMail.schedule(new TimerTask() {
            @Override
            public void run() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                    //没有悬浮窗权限时打开设置页面
                    if (!SettingsCompat.canDrawOverlays(getApplication())) {
                        preferences.edit().putBoolean("isWindowPermission", false).commit();
                        //1分钟后如果用户还没打开权限再弹出一次
                        if ((System.currentTimeMillis() - exitTime) > 1000 * 30 && r < 3) {
                            r++;
                            exitTime = System.currentTimeMillis();
                            Log.e(TAG, "run: 没有权限，请打悬浮窗权限页面------" + BaseUtil.getTopApp(getApplication(), MainActivity.class));
                            Intent intent = new Intent(getApplication(), MainActivity.class);
                            intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES | Intent.FLAG_ACTIVITY_NEW_TASK);
                            getApplication().startActivity(intent);
                        }
                    } else {
                        r = 0;
                        preferences.edit().putBoolean("isWindowPermission", true).commit();
                    }


//                    if (BaseUtil.isBackgroundRunning(getApplication())) {
//                        if (!BaseUtil.getTopApp(getApplication(), MainActivity.class)) {
//                            Log.i(TAG, "将app设置前台显示");
//                            ActivityManager am = (ActivityManager) getApplication().getSystemService(Context.ACTIVITY_SERVICE);
//                            am.moveTaskToFront(BaseUtil.getActivityTaskId(getApplication(), MainActivity.class), ActivityManager.MOVE_TASK_WITH_HOME);
//                        }
//                    } else {
//                        Log.i(TAG, "app没有运行，想打app");
//                        Intent intent = getApplication().getPackageManager().getLaunchIntentForPackage("com.wu.advapplication");
//                        if (intent != null) {
//                            intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES | Intent.FLAG_ACTIVITY_NEW_TASK);
//                            getApplication().startActivity(intent);
//                        } else {
//                            intent = new Intent(getApplication(), MainActivity.class);
//                            intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES | Intent.FLAG_ACTIVITY_NEW_TASK);
//                            getApplication().startActivity(intent);
//                        }
//                    }
                }
            }
        }, 0, 1000);

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy()");
        super.onDestroy();
        startService(new Intent(this, CustomTestService.class));
    }

    public static class InnerService extends Service {

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        @Override
        public void onCreate() {
            super.onCreate();
            Log.e(TAG, "InnerService 创建了");
            startForeground(SERVICE_ID, new Notification());
            stopSelf();
        }
    }
}